package service

import (
	"go-monitor/common/crypto"
	"go-monitor/common/utility"
	"go-monitor/server/g"
	"io/ioutil"
	"os"
	"path/filepath"
)

var authdir string

// InitAuth 初始化密钥验证
func InitAuth() {
	//定义本地存储key的路径
	authdir = filepath.Join("./var/auth/server", "/")
	// 判断本地Server 是否存在key
	if utility.PathExists(authdir+"/private.pem") && utility.PathExists(authdir+"/public.pem") {
		isExists, _ := Redis.Exists("ServerPrivateKey")
		if !isExists {
			//读取privateKey塞进Redis中
			privateKey, err := utility.ReadFileAsBytes(authdir + "/private.pem")
			if err != nil {
				g.Logger.Error("read privateKey fail:", err)
			} else {
				dbkey := "ServerPrivateKey"
				if !isExists {
					Redis.Set(dbkey, string(privateKey), 0)
				}
			}
		}

		//判断Redis中是否存在ServerPublicKey
		isExists, _ = Redis.Exists("ServerPublicKey")
		if !isExists {
			//读取publicKey塞进Redis中
			publicKey, err := utility.ReadFileAsBytes(authdir + "/public.pem")
			if err != nil {
				g.Logger.Error("read publicKey fail:", err)
			} else {
				dbkey := "ServerPublicKey"
				if !isExists {
					Redis.Set(dbkey, string(publicKey), 0)
				}
			}
		}
	} else {
		if !utility.PathExists(authdir) {
			err := os.MkdirAll(authdir, os.ModeDir)
			if err != nil {
				g.Logger.Error("auth server dir create fail:", err)
			}
		}
		crypto.GenRsaKey(512, authdir+"/")

		//读取privateKey塞进Redis中
		privateKey, err := utility.ReadFileAsBytes(authdir + "/private.pem")
		if err != nil {
			g.Logger.Error("read privateKey fail:", err)
		} else {
			dbkey := "ServerPrivateKey"
			isExists, _ := Redis.Exists(dbkey)
			if !isExists {
				Redis.Set(dbkey, string(privateKey), 0)
			}
		}

		serverauthdir := filepath.Join("./var/auth/agent", "/")
		if !utility.PathExists(serverauthdir) {
			err := os.MkdirAll(serverauthdir, os.ModeDir)
			if err != nil {
				g.Logger.Error("auth agent dir create fail:", err)
			}
		} else {
			//读取publicKey塞进Redis中
			publicKey, err := utility.ReadFileAsBytes(authdir + "/public.pem")
			if err != nil {
				g.Logger.Error("read publicKey fail:", err)
			} else {
				dbkey := "ServerPublicKey"
				isExists, _ := Redis.Exists(dbkey)
				if !isExists {
					Redis.Set(dbkey, string(publicKey), 0)
				}
			}

		}
	}
}

// AuthClientSaveKey 保存Agent的公钥
func AuthClientSaveKey(key []byte, path string) error {
	return ioutil.WriteFile(path, key, os.ModePerm)
}

// RsaEncrypt 加密-用Agent的公钥加密
func RsaEncrypt(origData []byte, agentPublicKey []byte) ([]byte, error) {
	return crypto.RsaEncrypt(origData, agentPublicKey)
}

// RsaDecrypt 解密-服务器私钥解密
func RsaDecrypt(ciphertext []byte, privateKey []byte) ([]byte, error) {
	return crypto.RsaDecrypt(ciphertext, privateKey)
}
